﻿<?php
/**
*	@package: sport
*	@subpackage: library
*	@class: Upload
*	@description: process upload image
*	@author: Pham Van Diep
*	@date: 12/2/2014
*	$usage:
*			$upload = new CI_Upload;
*			$upload->upload('file');
**/

class CI_Upload {
	// thu muc upload goc
	private $_root_upload_dir;
	// thu muc upload theo Nam/Thang/Ngay
	private $_current_upload_dir;
	// duong dan upload 
	private $_upload_path;
	// loai file cho phep
	private $_allow_type = array('image/gif','image/jpeg','image/jpg','image/png' );
	// dung luong cho phep
	private $_allow_size = IMAGE_MAX_UPLOAD_SIZE;//10M
	// chua thong tin loi
	private $_error_message = '';
	//chieu rong cua hinh
	private $_image_width = IMAGE_STANDARD_WIDTH;
	public function __construct() {
		// kiem tra thu muc ton tai
		$this->_root_upload_dir = realpath(IMAGE_UPLOAD_DIR);
		$this->_current_upload_dir = date("Y/m/d");		
		if( ! file_exists ($this->_root_upload_dir . DIRECTORY_SEPARATOR .$this->_current_upload_dir) ) {
			// tao thu muc				
			mkdir($this->_root_upload_dir . DIRECTORY_SEPARATOR .$this->_current_upload_dir,DIR_WRITE_MODE,TRUE);//0777
		}
		$this->_upload_path = realpath($this->_root_upload_dir . DIRECTORY_SEPARATOR .$this->_current_upload_dir ); 
	}	
	
	/*
	*	@author: Pham Van Diep
	*	@date: 12/2/2014
	*	@description: Lay thong tin loi	
	*	@return: Neu co loi tra ve chuoi chua thong tin loi, neu  khong tra ve chuoi rong
	*/
	public function getErrorMessage() {			
		return $this->_error_message;
	}
	/*
	*	@author: Pham Van Diep
	*	@date: 12/2/2014
	*	@description: Lay thu muc upload hien tai	
	*	@return: string path
	*/
	public function getUploadDir() {			
		return $this->_upload_path;
	}
	/*
	*	@author: Pham Van Diep
	*	@date: 12/2/2014
	*	@description: set kieu file cho phep upload
	*	@param: allow array : array("image/jpg","video/mpeg")
	*	@return: neu thanh cong tra ve 1, khong tra ve 0
	*/
	public function setAllowFileType($arrAllow = array()){
		if( count($arrAllow) <= 0) {
			return 0;
		}
		$this->_allow_type = $arrAllow;		
		return 1;
	}
	/**
	*	@author: Pham Van Diep	
	*	@date: 12/2/2014
	*	@dexcription: set dung luong lon nhat duoc phep upload, mac dinh la 10M
	*	@param: size int
	*	@return: neu thanh cong tra ve 1 nguoc lai tra ve 0
	*/
	public function setMaxFileSize($intSize){
		if( ! is_integer($intSize) ){
			return 0;
		}
		$this->_allow_size = $intSize; 		
		return 1;
	}
	/**
	*	@author: Pham Van Diep
	*	@date: 12/2/2014
	*	@description: upload file
	*	@param: string file field
	*	@example: <input type="file" name="upload"> => $strFile = upload
	*	@return: upload thanh cong tra ve mang chua thong tin cua hinh anh, nguoc lai tra ve mang rong
	*/
	public function do_upload( $strFile ){	
		//Kiem tra form submit
		if ( ! isset($_FILES[$strFile]) ) {
			//$this->_error_message = $arrLocale['upload_no_file'];
            $this->_error_message = 'No file upload.';
			return array();
		}
		// neu co loi	
		if( $_FILES[$strFile]['error'] > 0 ){
			$this->_error_message = $this->_getErrorMessageFromErrorCode($_FILES[$strFile]['error']);
			return array();
		}		
		// kiem tra kieu file
		if( ! in_array($_FILES[$strFile]['type'], $this->_allow_type ) ) {
			//$this->_error_message = $arrLocale['upload_disallow'];
            $this->_error_message = 'File type disallow';
			return array();
		}
		// kiem tra dung luong
		if( $_FILES[$strFile]['size'] > $this->_allow_size ) {
			//$this->_error_message = $arrLocale['upload_maxsize'];
            $this->_error_message = 'Max file size allow';
			return array();
		}
		$info = pathinfo($_FILES[$strFile]['name']);
		list($src_w, $src_h) = getimagesize($_FILES[$strFile]['tmp_name']);
        $first = md5($info['filename'].'_'.time());        
		$name = $first.'.'.$info['extension'];
		$new_path = $this->_current_upload_dir. '/' .$name;				
		if( ! move_uploaded_file($_FILES[$strFile]['tmp_name'],$this->_root_upload_dir. DIRECTORY_SEPARATOR .$new_path) ){
		//	$this->_error_message = $arrLocale['upload_failed'];
        	$this->_error_message = 'System error.';
			return array();
		}				
		// neu hinh anh khong dung kich thuoc thi resize
		if ( $src_w > $this->_image_width ) { 				
			$path = $this->_scale($new_path,$this->_image_width, $src_h);
			if ( $path !== '' ) {				
				$inf = pathinfo($this->_root_upload_dir. DIRECTORY_SEPARATOR .$path);
				$inf['width']    = $this->_image_width;
				$inf['height']   = $src_h;
                $inf['path']     = $this->_current_upload_dir. '/';
                $inf['realname'] = $inf['filename']; 
                $inf['firstname'] = $first;
				unlink($this->_root_upload_dir. DIRECTORY_SEPARATOR . $new_path);
				return $inf;
			}
		}
		$info['width'] = $src_w;
		$info['height'] = $src_h;
        $info['path']   = $this->_current_upload_dir. '/';
        $info['realname'] = rtrim($name,'.'.$info['extension']);
        $info['firstname'] = $first;
		return $info;
        		
	}
    
	/**
	*	@author: Pham Van Diep
	*	@date: 21/2/2014
	*	@description: get image from url		
	*	@param: string image link	
	*	@return: string
	*/
    public function do_upload_url($strLink) {
        if(!$strLink) {
            return array();
        }else{
            $arrInfo = pathinfo($strLink);
            /*if( ! in_array($arrInfo['extension'], $this->_allow_type ) ) {
			     $this->_error_message = $arrLocale['upload_disallow'];
		          return array();
            }*/
            $name = $arrInfo['filename'];
            $ext  = $arrInfo['extension'];
            $newName = md5($name.'_'.time());
            $content = file_get_contents($strLink);
            list($src_w,$src_h) = getimagesize($strLink);
            $fullPath = $this->_upload_path.'/'.$newName.'.'.$ext;
            $path     = $this->_current_upload_dir.'/'.$newName.'.'.$ext;            
            file_put_contents($fullPath, $content);
            $inf = pathinfo($fullPath);
                $inf['width']    = $src_w;
				$inf['height']   = $src_h;
                $inf['path']     = $this->_current_upload_dir. '/';
                $inf['realname'] = $inf['filename']; 
                $inf['firstname'] = $newName;
            if($src_w > IMAGE_STANDARD_WIDTH) {
                $resizePath = $this->_scale($path,IMAGE_STANDARD_WIDTH,$src_h);
                if ( $resizePath !== '' ) {				
    				$inf = pathinfo($this->_root_upload_dir.'/' .$resizePath);
    				$inf['width']    = IMAGE_STANDARD_WIDTH;
    				$inf['height']   = $src_h;
                    $inf['path']     = $this->_current_upload_dir. '/';
                    $inf['realname'] = $inf['filename']; 
                    $inf['firstname'] = $newName;
    				unlink($this->_root_upload_dir. '/' . $path);    				
    			}
            }
            return $inf;
            
        }
    }
	private function _scale($src,$width,$height){		
		if($width == $height) return $this->_crop($src,$width,$height);
		else return $this->_resize($src,$width,$height);
	}
	private function _resize($src, $width , $height ) {
		include_once('Thumbnail.php');
		$thumb = new CI_Thumbnail(realpath(IMAGE_UPLOAD_DIR  .$src));			
		$thumb->size($width , $height );
		$thumb->process();			
		$thumb->save(IMAGE_UPLOAD_DIR  .$src);		
		return IMAGE_UPLOAD_DIR  .$src;
	}
	private function _crop($src, $width = IMAGE_AVATAR_WIDTH, $height = IMAGE_AVATAR_WIDTH) {	
		include_once('Crop.php');
		$crop = new CI_Crop();				
		$crop->thumbSquare(IMAGE_UPLOAD_DIR . $src ,IMAGE_UPLOAD_DIR . $src, $width, $height) ;		
		return IMAGE_UPLOAD_DIR . $src;		
	}
	/**
	*	@author: Pham Van Diep
	*	@date: 12/2/2014
	*	@description: Lay thong tin loi tu ma loi		
	*	@param: int ma loi	
	*	@return: string
	*/
	private function _getErrorMessageFromErrorCode ($intCode ) {
		switch( $intCode) {
			case UPLOAD_ERR_OK:
				return $arrLocale['upload_success'];
				break;
			case UPLOAD_ERR_INI_SIZE:
				return $arrLocale['upload_maxsize'];
				break;
			case UPLOAD_ERR_FORM_SIZE:
				return $arrLocale['upload_maxsize'];
				break;
			case UPLOAD_ERR_PARTIAL:
				return $arrLocale['upload_patial'];
				break;
			case UPLOAD_ERR_NO_FILE:
				return $arrLocale['upload_no_file'];
				break;
			case UPLOAD_ERR_NO_TMP_DIR:
				return $arrLocale['upload_missing_tmp_dir'];
				break;
			case UPLOAD_ERR_CANT_WRITE:
				return $arrLocale['upload_write_failed'];
				break;
			case UPLOAD_ERR_EXTENSION:
				return $arrLocale['upload_php_ext_stop'];
				break;
			default:
				return '';
		
		}
	}	
	
	
	
}
/* ****************************** End of upload class ************************** */